package com.test.application.metadata_extractor;

import com.alibaba.fastjson2.JSONObject;

import com.drew.imaging.ImageMetadataReader;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.Tag;
import com.drew.metadata.exif.GpsDirectory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

@RestController
@RequestMapping("/location")
public class ImgLocationController {

    @Resource
    private RestTemplate restTemplate;

    @RequestMapping("/getLocationByImg")
    public String getLocationByImg(MultipartFile imgFile) throws Exception {
        if (imgFile == null) {
            return "图片为空";
        }
        return  readImageInfo(imgFile);
    }

    private  String readImageInfo(MultipartFile file) throws Exception {
        Metadata metadata = ImageMetadataReader.readMetadata(file.getInputStream());
        System.out.println("---打印全部详情---");
        for (Directory directory : metadata.getDirectories()) {
            if (directory instanceof GpsDirectory) {
                GpsDirectory gpsDirectory = (GpsDirectory) directory;

                // 获取GPS纬度
                String latitudeRef = gpsDirectory.getString(GpsDirectory.TAG_LATITUDE_REF);
                double latitude = gpsDirectory.getDouble(GpsDirectory.TAG_LATITUDE);

                // 获取GPS经度
                String longitudeRef = gpsDirectory.getString(GpsDirectory.TAG_LONGITUDE_REF);
                double longitude = gpsDirectory.getDouble(GpsDirectory.TAG_LONGITUDE);

                String altitudeRef = gpsDirectory.getString(GpsDirectory.TAG_ALTITUDE_REF);
                double altitude = gpsDirectory.getDouble(GpsDirectory.TAG_ALTITUDE);

                // 输出结果
                System.out.println("Latitude Reference: " + latitudeRef);
                System.out.println("Latitude: " + latitude);
                System.out.println("Longitude Reference: " + longitudeRef);
                System.out.println("Longitude: " + longitude);
                System.out.println("Altitude Reference: " + altitudeRef);
                System.out.println("Altitude: " + altitude);
            }
            for (Tag tag : directory.getTags()) {
                System.out.format("[%s] - %s = %s\n", directory.getName(), tag.getTagName(), tag.getDescription());
            }
            if (directory.hasErrors()) {
                for (String error : directory.getErrors()) {
                    System.err.format("ERROR: %s", error);
                }
            }
        }
        System.out.println("--打印常用信息---");
        Double lat = null;
        Double lng = null;
        for (Directory directory : metadata.getDirectories()) {
            for (Tag tag : directory.getTags()) {
                String tagName = tag.getTagName();  //标签名
                String desc = tag.getDescription(); //标签信息
                switch (tagName) {
                    case "Image Height":
                        System.err.println("图片高度: " + desc);
                        break;
                    case "Image Width":
                        System.err.println("图片宽度: " + desc);
                        break;
                    case "Date/Time Original":
                        System.err.println("拍摄时间: " + desc);
                        break;
                    case "GPS Latitude":
                        System.err.println("纬度 : " + desc);
                        System.err.println("纬度(度分秒格式) : " + pointToLatlong(desc));
                        lat = latLng2Decimal(desc);
                        break;
                    case "GPS Longitude":
                        System.err.println("经度: " + desc);
                        System.err.println("经度(度分秒格式): " + pointToLatlong(desc));
                        lng = latLng2Decimal(desc);
                        break;
                }
            }
        }
        System.err.println("--经纬度转地址--");
        //经纬度转地主使用百度api
        if (lat == null || lng == null) {
            return "经纬度信息为空,无法获取位置信息";
        }
        return convertGpsToLocation(lat, lng);
    }
    public  String pointToLatlong(String point) {
        double du = Double.parseDouble(point.substring(0, point.indexOf("°")).trim());
        double fen = Double.parseDouble(point.substring(point.indexOf("°") + 1, point.indexOf("'")).trim());
        double miao = Double.parseDouble(point.substring(point.indexOf("'") + 1, point.indexOf("\"")).trim());
        double duStr = du + fen / 60 + miao / 60 / 60;
        return Double.toString(duStr);
    }

    /***     * 经纬度坐标格式转换（* °转十进制格式）     * @param gps     */
    public  double latLng2Decimal(String gps) {
        String a = gps.split("°")[0].replace(" ", "");
        String b = gps.split("°")[1].split("'")[0].replace(" ", "");
        String c = gps.split("°")[1].split("'")[1].replace(" ", "").replace("\"", "");
        return Double.parseDouble(a) + Double.parseDouble(b) / 60 + Double.parseDouble(c) / 60 / 60;
    }


    /**
     *       api_key：注册的百度api的key
     *       coords：经纬度坐标
     *       http://api.map.baidu.com/reverse_geocoding/v3/?ak="+api_key+"&output=json&coordtype=wgs84ll&location="+coords
     * @param gps_latitude  维度
     * @param gps_longitude 经度
     * @return 地址
     */
    private  String convertGpsToLocation(double gps_latitude, double gps_longitude) {
        String location = "";
        String apiKey = "YNxcSCAphFvuPD4LwcgWXwC3SEZZc7Ra";//百度地图apiKey
        String res;
        String url = "http://api.map.baidu.com/reverse_geocoding/v3/?ak=" + apiKey + "&output=json&coordtype=wgs84ll&location=" + (gps_latitude + "," + gps_longitude);
        System.err.println("【url】" + url);
        res = restTemplate.getForObject(url, String.class);
        JSONObject object = JSONObject.parseObject(res);
        if (object != null && object.containsKey("result")) {
            JSONObject result = object.getJSONObject("result");
            if (result.containsKey("addressComponent")) {
                JSONObject address = object.getJSONObject("result").getJSONObject("addressComponent");
                location = "拍摄地点：" + address.get("country") + " " + address.get("province") + " " + address.get("city") + " " + address.get("district") + " " + address.get("street") + " " + result.get("formatted_address") + " " + result.get("business");
                System.err.println(location);
            }
        }
        return location;
    }
}